package com.xlh.openai.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.xlh.openai.builder.TextBuilder;
import com.xlh.openai.service.WechatUserService;
import com.xlh.openai.service.impl.WebChatServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private WechatUserService wechatUserService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    @Lazy
    private WxMpService wxMpService;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info( "新关注用户 OPENID: " + wxMessage.getFromUser() );
        this.logger.info( "输出可能被扫描的微信场景 : " + context );
        String sceneStr = wxMessage.getEventKey();
        if(StrUtil.isNotBlank(sceneStr)){
            WebChatServiceImpl.putSceneIdMap( sceneStr, wxMessage.getFromUser());
            System.out.println("场景扫描ID+++");
        }
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                wechatUserService.save(userWxInfo.getOpenId());
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {

            Thread conversationThread = new Thread(() -> {
                // 创建线程池
                try {
                    // 推送提示语
                    WxMpKefuMessage message = WxMpKefuMessage
                            .TEXT()
                            .toUser(wxMessage.getFromUser())
                            .content("感谢关注码头AI,新关注的用户我们会赠送10次免费问答的机会,您的每次使用都是对我们最好的鼓励！")
                            .build();
                    wxMpService.getKefuService().sendKefuMessage(message);
                    // 推送图文消息
                    WxMpKefuMessage.WxArticle item = new WxMpKefuMessage.WxArticle();
                    item.setDescription("指导教程");
                    item.setPicUrl("https://mmbiz.qpic.cn/mmbiz_jpg/BBwSjkZnqbROKWeeVak0EbEsmMcaUNQNlQwVyEiccXdp58dyoWSFtjjVSYLkgXJzzqUuiayU4nhQ9radSySibIt9A/0?wx_fmt=jpeg");
                    item.setTitle("【全网最全攻略】一文了解ChatGPT，手把手教你通关！");
                    item.setUrl("https://mp.weixin.qq.com/s?__biz=MzkwMjQ2NjMwMg==&mid=2247483713&idx=1&sn=dcfac094ddfafe496483efc995a8c72b&chksm=c0a45ed0f7d3d7c6a052e58f49ddca126c7ef53b520477d0706df2c35fd05a9e18110310dee7#rd");
                    // 推送图文消息
                    WxMpKefuMessage.WxArticle itemSecond = new WxMpKefuMessage.WxArticle();
                    itemSecond.setDescription("指导教程");
                    itemSecond.setPicUrl("https://mmbiz.qpic.cn/mmbiz_jpg/BBwSjkZnqbROKWeeVak0EbEsmMcaUNQNeQ9hVnbgQicHBcnTKicQR5CKGAuLNmJSic4MWSXKURPWCqY7atrVUfiaIw/0?wx_fmt=jpeg");
                    itemSecond.setTitle("【教师ChatGPT实用指南】如何利用ChatGPT快速设计课程");
                    itemSecond.setUrl("https://mp.weixin.qq.com/s?__biz=MzkwMjQ2NjMwMg==&mid=2247483713&idx=2&sn=1dcf7a6ce6734684cd5cef8dc4cec351&chksm=c0a45ed0f7d3d7c6642198b992de4fc4a9a37c87bafa7cc418bc56b75a10eea30aeca072dc31&token=1412693275&lang=zh_CN#rd");

                    WxMpKefuMessage build = WxMpKefuMessage
                            .NEWS()
                            .toUser(wxMessage.getFromUser())
                            .addArticle(item)
                            .build();
                    wxMpService.getKefuService().sendKefuMessage(build);

                    WxMpKefuMessage buildSecond = WxMpKefuMessage
                            .NEWS()
                            .toUser(wxMessage.getFromUser())
                            .addArticle(itemSecond)
                            .build();
                    wxMpService.getKefuService().sendKefuMessage(buildSecond);

                } catch (WxErrorException e) {
                    logger.error("回复客服消息失败！", e);
                }
            });
            threadPoolTaskExecutor.execute(conversationThread);
            return null;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
